package com.hzx.demo.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.hzx.demo.R;
import com.hzx.demo.util.Entry;
import com.hzx.demo.util.HZXLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

/*
 * Created by ldkxingzhe on 2016/5/20.
 */
@Entry(desc = "测试使用Shader进行图片的处理, 主要是ComposeShader", createTime = "2016-05-20")
@EActivity(R.layout.activity_shader)
public class ShaderActivity extends AppCompatActivity{
    @SuppressWarnings("unused")
    private static final String TAG = "ShaderActivity";

    @ViewById(R.id.iv_shader)
    ImageView mImageView;

    @AfterViews
    protected void afterView(){
        HZXLog.v(TAG, "afterView");
        mImageView.setImageDrawable(new FontMaskDrawable());
    }

    private class FontMaskDrawable extends Drawable{

        private Paint mPaint;
        private PorterDuffXfermode mPorterDuffXfermode;

        public FontMaskDrawable(){
            mPaint = new Paint();
            mPorterDuffXfermode = new PorterDuffXfermode((PorterDuff.Mode.DST_OUT));
            mPaint.setAntiAlias(true);
            mPaint.setTextSize(30);
        }
        @Override
        public void draw(Canvas canvas) {
            canvas.saveLayer(0, 0, 400, 400, mPaint);
//            canvas.save();
            canvas.drawBitmap(makeBitmap(Color.BLUE), 0, 0, mPaint);
            mPaint.setXfermode(mPorterDuffXfermode);
            canvas.drawText("明月照我心", 10, 50, mPaint);
            mPaint.setXfermode(null);
            canvas.restore();
            HZXLog.v(TAG, "draw");
        }

        private Bitmap makeBitmap(int color){
            Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(color);
            return bitmap;
        }

        @Override
        protected void onBoundsChange(Rect bounds) {
            super.onBoundsChange(bounds);
            HZXLog.v(TAG, "onBoundsChange");
        }

        @Override
        public void setAlpha(int alpha) {
            // ignore
        }

        @Override
        public void setColorFilter(ColorFilter colorFilter) {
            // ignore
        }

        @Override
        public int getOpacity() {
            return PixelFormat.OPAQUE;
        }
    }
}
